package cn.heycm.blog.common.web.exception;

import cn.heycm.blog.common.entity.error.ServiceException;
import cn.heycm.blog.common.entity.result.CodeMsg;
import cn.heycm.blog.common.entity.result.Result;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * 全局异常处理
 *
 * @author hey
 * @version 1.0
 * @since 2024/9/15 16:42
 */
@RestControllerAdvice
@Slf4j
public class WebExceptionHandler {

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Throwable.class)
    public Result<Object> error(Throwable e) {
        log.error("Throwable 发生未知异常！", e);
        return Result.error(CodeMsg.UNKNOWN_ERROR);
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result<Object> error(Exception e) {
        log.error("Exception 发生未知异常！", e);
        return Result.error(CodeMsg.UNKNOWN_ERROR);
    }

    @ExceptionHandler(ServiceException.class)
    public Result<Object> error(ServiceException e) {
        return Result.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    public Result<Object> handleValidatedException(Exception e) {
        String message = switch (e) {
            case MethodArgumentNotValidException ex ->
                // BeanValidation exception
                    getParamError(ex.getBindingResult());
            case ConstraintViolationException ex ->
                // BeanValidation GET simple param
                    ex.getConstraintViolations().stream()
                            .map(ConstraintViolation::getMessage)
                            .collect(Collectors.joining("; "));
            case BindException ex ->
                // BeanValidation GET object param
                    getParamError(ex.getBindingResult());
            case null, default -> CodeMsg.INVALID_PARAM.getMsg();
        };
        return Result.error(CodeMsg.INVALID_PARAM.getCode(), message);
    }

    private String getParamError(BindingResult br) {
        List<FieldError> fieldErrors = br.getFieldErrors();
        if (CollectionUtils.isEmpty(fieldErrors)) {
            return "参数错误";
        }
        StringJoiner joiner = new StringJoiner(";");
        for (FieldError fieldError : fieldErrors) {
            String field = fieldError.getField();
            String message = fieldError.getDefaultMessage();
            if (message != null && message.contains("java.lang.NumberFormatException")) {
                message = "参数类型异常";
            }
            joiner.add(field + ":" + message);
        }
        return joiner.toString();
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result<Object> error(MissingServletRequestParameterException e) {
        return Result.error(CodeMsg.INVALID_PARAM.getCode(), "缺少参数: " + e.getParameterName());
    }

    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<Object> error(HttpRequestMethodNotSupportedException e) {
        return Result.error(405, "Method Not Allowed: " + e.getMessage());
    }

    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public Result<Object> error(HttpMediaTypeNotSupportedException e) {
        return Result.error(415, "Unsupported Media Type: " + e.getMessage());
    }

    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoResourceFoundException.class)
    public Result<Object> error(NoResourceFoundException e) {
        return Result.error(CodeMsg.RESOURCE_NOT_FOUND);
    }
}
